import { NextRequest, NextResponse } from 'next/server';
import { verifyAuth } from '@/lib/auth-middleware';
import { getUserManagement } from '@/lib/user-management';

export async function GET(request: NextRequest) {
  try {
    const authResult = await verifyAuth();
    
    if (!authResult.success || !authResult.user) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    const { searchParams } = new URL(request.url);
    const tableName = searchParams.get('tableName');
    const dataSource = searchParams.get('dataSource');

    const userMgmt = getUserManagement();
    const permissions = userMgmt.parseRolePermissions(authResult.user.role_permissions);

    let editableFields: string[] = [];
    let hasDataSourceAccess = true;

    // 检查数据来源权限
    if (dataSource) {
      hasDataSourceAccess = permissions.canEditAll || permissions.dataSourceAccess.includes(dataSource);
    }

    // 获取可编辑字段
    if (tableName && hasDataSourceAccess) {
      editableFields = userMgmt.getUserEditableFields(authResult.user, tableName);
    }

    return NextResponse.json({
      success: true,
      data: {
        user: {
          id: authResult.user.id,
          username: authResult.user.username,
          full_name: authResult.user.full_name,
          role_code: authResult.user.role_code,
          role_name: authResult.user.role_name
        },
        permissions: {
          canEditAll: permissions.canEditAll,
          canManageUsers: permissions.canManageUsers,
          canManageRoles: permissions.canManageRoles,
          dataSourceAccess: permissions.dataSourceAccess,
          hasDataSourceAccess,
          editableFields
        }
      }
    });

  } catch (error) {
    console.error('获取权限信息失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取权限信息失败'
    }, { status: 500 });
  }
}
